package com.quan.weixin.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.utils.Paginator;
import com.quan.base.common.utils.file.FileUpload;
import com.quan.base.common.utils.file.FileUtils;
import com.quan.base.common.utils.file.FileVo;
import com.quan.upms.annotation.RequiresPermissions;
import com.quan.weixin.api.API;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.common.WeixinUtil;
import com.quan.weixin.model.Media;
import com.quan.weixin.rpc.api.WeixinMediaService;
import com.quan.weixin.rpc.extend.BatchDeleteVo;
import com.quan.weixin.rpc.model.WeixinMedia;
import com.quan.weixin.tools.WeiXinTools;

@RestController
@RequestMapping(value = "/api/weixin/media")
public class WeixinMediaController extends BaseController {

	@Autowired
	private WeixinMediaService weixinMediaService;

	@RequiresPermissions(value="weixin:media:add", description="添加微信素材")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinMedia entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinMediaService.insertSelective(entity);

		return BaseResult.ok();
	}

	@RequiresPermissions(value="weixin:media:delete", description="删除微信素材")
	@GetMapping(value = "/delete/{id}/{mediaId}")
	public Object delete(@PathVariable Integer id, @PathVariable String mediaId) {
		
		this.weixinMediaService.delete(id);
		
		JSONObject deleteMedia = WeiXinTools.deleteMedia(WeixinContext.getAccessToken(), mediaId) ;
		if(deleteMedia.getInteger("errcode") == 0) {
			return BaseResult.ok("删除素材成功") ;
		} else {
			return BaseResult.failure("删除素失败"+deleteMedia.getString("errmsg")) ;
		}
	}
	
	@RequiresPermissions(value="weixin:text:delete", description="删除微信素材")
	@PostMapping(value = "/deleteBatch")
	public Object deleteBatch(@RequestBody BatchDeleteVo vo) {
		List<Integer> delIds = new ArrayList<Integer>() ;
		
		List<String> mediaIds = vo.getMediaIds();
		for(int i=0; i< mediaIds.size(); i++) {
			JSONObject deleteMedia = WeiXinTools.deleteMedia(WeixinContext.getAccessToken(), mediaIds.get(i)) ;
			Integer errcode = deleteMedia.getInteger("errcode") ;
			if(errcode == 0) {
				delIds.add(vo.getIds().get(i)) ;
			}
		}
		
		if(!delIds.isEmpty()) {
			this.weixinMediaService.deleteByIds(StringUtils.join(delIds.toArray(), ",")) ;
			return BaseResult.ok("删除永久素成功，删除数量：[ "+delIds.size()+" ]") ;
		} else {
			return BaseResult.failure("删除永久素失败") ;
		}
	}

	@RequiresPermissions(value="weixin:media:update", description="修改微信素材")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinMedia entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinMediaService.updateSelective(entity);

		return BaseResult.ok();
	}

	@RequiresPermissions(value="weixin:media:detail", description="查询微信素材详情")
	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinMediaService.selectById(id);
	}
	
	@RequiresPermissions(value="weixin:media:list", description="查询微信素材")
	@GetMapping(value = "/list")
	public Object list(WeixinMedia entity) {
		return this.weixinMediaService.selectPage(new Paginator(request), entity) ;
	}
	
	/**
	 * 上传素材
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/uploadMedia")
	public Object uploadArticlePic(HttpServletRequest request, String mediaType, String remarks) {
		if(!StringUtils.isNotBlank(mediaType)) {
			return BaseResult.failure("素材类型为必填项") ;
		}
		FileVo fileVo = FileUpload.upload(request, "/weixin/newsImg") ;
		
		// TODO 图片压缩
		
		String uploadMedia = API.get(API.UPLOAD_MEDIA_URL, WeixinContext.getAccessToken(), mediaType) ;
		String httpRequest = WeixinUtil.httpRequest(uploadMedia, new File(fileVo.getFullPath())) ;
		Object json = JSON.toJSON(httpRequest);
		Media mediaMsg = JSON.parseObject(json.toString(), Media.class);
		
		if(mediaMsg.getErrcode() > 0) {
			return BaseResult.failure(mediaMsg.getErrcode() + "==>" + mediaMsg.getErrmsg()) ;
		} else {
			WeixinMedia media = new WeixinMedia() ;
			media.setMediaId(mediaMsg.getMedia_id());
			media.setUrl(mediaMsg.getUrl());
			media.setMediaType(mediaType);
			media.setRemarks(remarks);
			this.weixinMediaService.insertSelective(media) ;
		}
		
		FileUtils.deleteFile(fileVo.getFullPath());
		
		return BaseResult.ok() ;
	}
}
